package com.hl.mytools.ui

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.hl.lib.base.BaseActivityBM
import com.hl.lib.ext.hideLoading
import com.hl.lib.utils.net.WebPageUtil
import com.hl.mytools.data.Urls
import com.hl.mytools.database.FundInfo
import com.hl.mytools.databinding.ActivityMainBinding
import com.hl.mytools.databinding.ItemFundListBinding


class MainActivity : BaseActivityBM<ActivityMainBinding, MainActivityViewModel>() {
    companion object {
        private const val TAG = "MainActivity"
    }

    private var mAdapter: FundAdapter = FundAdapter(mutableListOf<FundInfo>())

    private var start = System.currentTimeMillis()

    override val mViewModel: MainActivityViewModel by viewModels()

    override fun provideViewBinding(): ActivityMainBinding {
        return ActivityMainBinding.inflate(layoutInflater)
    }

    override fun initData() {
        start = System.currentTimeMillis()
        showLoading("loading...")
        mViewModel.queryFoundInfo()
    }

    override fun initView() {

        mBinding.apply {
            btnSubject.setOnClickListener {
                WebPageUtil.openUrl(mContext,Urls.hot_Subject)
            }
            btnBuy.setOnClickListener {}
            btnSale.setOnClickListener {}
            btnAdd.setOnClickListener {}
            smartLayout.setOnRefreshListener {
                // 下拉刷新
                mViewModel.queryFoundInfo()
            }

            rvFunds.apply {
                layoutManager =
                    LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
                addItemDecoration(
                    DividerItemDecoration(
                        mContext, DividerItemDecoration.VERTICAL
                    )
                );
                adapter = mAdapter
                mAdapter.setOnClickListener(object : RvListener {
                    override fun onItemClick(view: View, position: Int) {
                        val url =
                            Urls.tonghua_fund_detail_url + mViewModel.fundList[position].code
                        WebPageUtil.openUrl(mContext,url)
                    }
                })
            }
        }


    }



    override fun observeViewModel() {
        mViewModel.state.observe(this@MainActivity) {
            if (it) {
                val time = (System.currentTimeMillis() - start) / 1000F
//                Log.e(TAG, "observeViewModel: ============================")
//                Log.e(TAG, "observeViewModel: ============================")
//                Log.e(TAG, "observeViewModel: ============================")
//                Log.e(TAG, "observeViewModel: ============================")
//                mViewModel.soredFundList.forEach { fundInfo ->
//                    Log.e(TAG, "observeViewModel: ${JSON.toJSONString(fundInfo)}")
//                }

//                mViewModel.soredFundList.sortBy { it.adviceReason }
//                mAdapter.updateData(mViewModel.soredFundList)
                mViewModel.fundList.sortByDescending { it.adviceReason }
                mAdapter.updateData(mViewModel.fundList)
                mBinding.smartLayout.finishRefresh()
                hideLoading()
            }
        }
    }

    override fun onNetStateChanged(connected: Boolean) {
//        ToastUtil.showShort(ContextUtil.get(), "网络变化了 $connected")
    }

}

private class FundAdapter(var fundList: MutableList<FundInfo>) :
    RecyclerView.Adapter<FundAdapter.FundViewHolder>() {

    var listener: RvListener? = null

    fun setOnClickListener(callback: RvListener) {
        listener = callback
    }

    fun updateData(dataList: MutableList<FundInfo>) {
        fundList.clear()
        fundList.addAll(dataList)
        notifyDataSetChanged()
    }

    inner class FundViewHolder(val itemBinding: ItemFundListBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {
    }

    override fun onCreateViewHolder(parent: ViewGroup, position: Int): FundViewHolder {
        val binding =
            ItemFundListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return FundViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return fundList.size
    }

    override fun onBindViewHolder(holder: FundViewHolder, position: Int) {
        listener?.let {
            holder.itemView.setOnClickListener { view ->
                it.onItemClick(view, position)
            }
        }

        holder.itemBinding.apply {

            fundList[position].let { curData ->
                tvFundName.text = curData.name
                tvFundCode.text = curData.code
                val price8 = curData.fundPriceInfoList?.get(7)?.jjjz
                val price7 = curData.fundPriceInfoList?.get(6)?.jjjz
                val price6 = curData.fundPriceInfoList?.get(5)?.jjjz
                val price5 = curData.fundPriceInfoList?.get(4)?.jjjz
                val price4 = curData.fundPriceInfoList?.get(3)?.jjjz
                val price3 = curData.fundPriceInfoList?.get(2)?.jjjz
                val price2 = curData.fundPriceInfoList?.get(1)?.jjjz
                val price1 = curData.fundPriceInfoList?.get(0)?.jjjz
                tvPrice1.text = price6
                tvPrice1.setTextColor(getPriceColor(price6!!.toDouble(), price7!!.toDouble()))
                tvPrice2.text = price5
                tvPrice2.setTextColor(getPriceColor(price5!!.toDouble(), price6.toDouble()))
                tvPrice3.text = price4
                tvPrice3.setTextColor(getPriceColor(price4!!.toDouble(), price5.toDouble()))
                tvPrice4.text = price3
                tvPrice4.setTextColor(getPriceColor(price3!!.toDouble(), price4.toDouble()))
                tvPrice5.text = price2
                tvPrice5.setTextColor(getPriceColor(price2!!.toDouble(), price3.toDouble()))
                tvPrice6.text = price1
                tvPrice6.setTextColor(getPriceColor(price1!!.toDouble(), price2.toDouble()))

                tvAdvice.text = curData.adviceReason
                if (curData.adviceKind == "买") {
                    tvAdvice.setTextColor(GREEN_COLOR)
                } else {
                    tvAdvice.setTextColor(RED_COLOR)
                }

                tvTrade.text = curData.trade
                tvSource.text = curData.source
            }
        }
    }

    val GREEN_COLOR = Color.parseColor("#00ff00")
    val RED_COLOR = Color.parseColor("#FF0000")

    //  var getColor: (val1: Double, val2: Double) -> String =if (val1 >= val2) "#FFFFEB3B" else "#FF4CAF50"
    val getPriceColor: (val1: Double, val2: Double) -> Int = { val1: Double, val2: Double ->
        if (val1 >= val2) RED_COLOR else GREEN_COLOR
    }

}

private interface RvListener {
    fun onItemClick(view: View, position: Int)
}